package com.cmcc.sdtp.sdtp.message;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.xml.bind.DatatypeConverter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.cmcc.sdtp.db.SaveExcThread;
import com.cmcc.sdtp.util.SdtpPropertiesUtil;
import com.cmcc.xdr.entity.StatXdrexclogEntity;
import com.cmcc.xdr.message.SingleSigGlobalMsg;
import com.cmcc.xdr.message.SingleSigMsg;
import com.cmcc.xdr.message.SynComposedMsg;
import com.cmcc.xdr.util.Interface;
import com.cmcc.xdr.util.XdrSingleSigMsgParseUtil;

public class XDRDataNotifyReqMsg extends MessageBody {

	private SingleSigGlobalMsg globalMsg;
	public Set<Object> interfaces = new HashSet<Object>();
	private static Logger logger = LogManager.getLogger(XDRDataNotifyReqMsg.class);

	private static String divisionXdrtype = SdtpPropertiesUtil.getProperty("IF_DIVISION_XDRTYPE");// 是否开启合成接口数据入库
	private static String xdrVersion = SdtpPropertiesUtil.getProperty("xdr.version");// 是否开启合成接口数据入库

	public XDRDataNotifyReqMsg() {
		super();
	}

	public XDRDataNotifyReqMsg(SDTPMessage message) {
		JJJJManage manage = JJJJManage.getInstance();// deal sv and other
		JJJJManageForComposedCall manageForComposedCall = JJJJManageForComposedCall.getInstance();// deal ComposedCall
//		JJJJManageForComposedReg manageForComposedReg = JJJJManageForComposedReg.getInstance();//deal ComposedReg and other composed
		JJJJManageForAuthen manageForAuthen = JJJJManageForAuthen.getInstance();// lvpin add 20170802 deal xdr_authen
		JJJJManageForPCC manageForPCC = JJJJManageForPCC.getInstance();// lvpin add 20170802 deal xdr_pcc
		JJJJManageForSIP manageForSIP = JJJJManageForSIP.getInstance();// lvpin add 20170802 deal xdr_sipcall xdr_sipreg
																		// xdr_sipsrvcc
		this.message = message;
		for (int i = 0; i < message.getTotalContents(); i++) {

			List<SingleSigMsg> singleSigMsgs = XdrSingleSigMsgParseUtil.parse(message.getBuffer(), divisionXdrtype,
					xdrVersion);
			globalMsg = singleSigMsgs.get(0).getSSGMsg();
			String tableName = "";
			try {
				logger.info("数据解析完成，进行入库操作接口类 " + globalMsg.getInterfaceType());
				int interfaceInt = 0;
				// Dpi单接口监控
				if (globalMsg.getInterfaceType() != null) {
					interfaceInt = globalMsg.getInterfaceType();
				}
				// Dpi合成接口监控
				if (globalMsg.getXdrInfoType() != 2) {
					// 0在这里赋予composed，监控合成xdr链接
					interfaceInt = 0;
				}
				if (Interface.getName(interfaceInt) != null) {
					interfaces.add(Interface.getName(interfaceInt));
				}
				if (globalMsg.getXdrInfoType() == 2) {// 单接口信息
					/**
					 * ================================================= =========单接口 Message Body
					 * 信息处理==开始============ =================================================
					 */

					if (globalMsg.getInterfaceType() == 29 || globalMsg.getInterfaceType() == 13
							|| globalMsg.getInterfaceType() == 14 || globalMsg.getInterfaceType() == 15
							|| globalMsg.getInterfaceType() == 16 || globalMsg.getInterfaceType() == 17
							|| globalMsg.getInterfaceType() == 18 || globalMsg.getInterfaceType() == 27) {
						for (SingleSigMsg msg : singleSigMsgs) {
							manageForSIP.addToList(msg);
						}
					}

					if (globalMsg.getInterfaceType() == 19) {
						for (SingleSigMsg msg : singleSigMsgs) {
							manage.addToList(msg);
						}
					}

					if (globalMsg.getInterfaceType() == 24 || globalMsg.getInterfaceType() == 20
							|| globalMsg.getInterfaceType() == 21 || globalMsg.getInterfaceType() == 22
							|| globalMsg.getInterfaceType() == 23) {
						for (SingleSigMsg msg : singleSigMsgs) {
							manageForAuthen.addToList(msg);
						}
					}

					if (globalMsg.getInterfaceType() == 26) {
						for (SingleSigMsg msg : singleSigMsgs) {
							manageForPCC.addToList(msg);
						}
					}

					if (globalMsg.getInterfaceType() == 28) {
						for (SingleSigMsg msg : singleSigMsgs) {
							manage.addToList(msg);
						}
					}
					/**
					 * ================================================= =========单接口 Message Body
					 * 信息处理==结束============ =================================================
					 */
				} else if (globalMsg.getXdrInfoType() == 1) {
					/**
					 * ================================================= =========合成接口 Message Body
					 * 信息处理==开始============ =================================================
					 */
					int procedureType = globalMsg.getProcedureType();
					if (procedureType == 5) {
						for (SingleSigMsg msg : singleSigMsgs) {
							manageForComposedCall.addToList(msg);
						}
					}

					/**
					 * ================================================= =========合成接口 Message Body
					 * 信息处理==结束============ =================================================
					 */
				} else {
					logger.error("--globalMsg---message-----"
							+ DatatypeConverter.printHexBinary(message.getBuffer().array()));
				}
			} catch (Exception e) {
				logger.error("XDRDataNotifyReqMsg数据解析异常----", e);
				logger.error("message.getTotalContents()-----" + message.getTotalContents()
						+ ",message.getBuffer().remaining()----" + message.getBuffer().remaining());
				logger.error("-------------message-----------" + i + "\r\n"
						+ DatatypeConverter.printHexBinary(message.getBuffer().array()));
				try {
					if (globalMsg != null && globalMsg.getInterfaceType() != null) {
						StatXdrexclogEntity statXdrexclog = new StatXdrexclogEntity();
						statXdrexclog.setTablename(tableName);
						statXdrexclog.setInterFace(globalMsg.getInterfaceType() + "");
						statXdrexclog.setExccount(1);
						String errorInfo = e.getMessage();
						if (errorInfo != null) {
							if (errorInfo.length() > 80)
								errorInfo = errorInfo.substring(0, 80);
							errorInfo = errorInfo.replaceAll("'", "");
							statXdrexclog.setExcreason(errorInfo);
						}
//						if(errorInfo.length() > 80)
//							errorInfo = errorInfo.substring(0, 80);
//						errorInfo = errorInfo.replaceAll("'", "");
//						statXdrexclog.setExcreason(errorInfo);
						statXdrexclog.setInserttime(new Date());
						SaveExcThread.saveExc(statXdrexclog);
//						SaveExcThread dbi = new SaveExcThread(statXdrexclog);
//						dbi.start();
					}

				} catch (Exception e2) {
					logger.error("XDRDataNotifyReqMsg数据入库异常=将插入异常信息到异常统计表,解析异常----", e2);
				}
			}
		}
	}

	/**
	 * 返回消息体长度
	 */
	@Override
	public int getLength() {
		return globalMsg.getTotalLength();
	}

	@Override
	public void encode() {

	}

	public SingleSigGlobalMsg getGlobalMsg() {
		return globalMsg;
	}

	public void setGlobalMsg(SingleSigGlobalMsg globalMsg) {
		this.globalMsg = globalMsg;
	}

	public String getServiceScenario(List<SynComposedMsg> list) {
		// 暂时去掉排序
		/*
		 * Collections.sort(list, new Comparator<SynComposedMsg>() {
		 * 
		 * @Override public int compare(SynComposedMsg o1, SynComposedMsg o2) { long i=
		 * o1.getComposed().getSingleStartTime().getTime() -
		 * o2.getComposed().getSingleStartTime().getTime() ; if (i == 0) { return
		 * o1.getComposed().getInterface() - o2.getComposed().getInterface(); } return
		 * (int) i; }
		 * 
		 * });
		 */
		String serviceScenario = "";
		// 判断是否为失败合成xdr
		int length = list.size();
		if (length > 0 && list.get(length - 1).composed.getProcedureType() == 5) {
			// if (list.get(length - 1).composed.getProcedureStatus() == 2 || list
			// .get(length - 1).composed.getProcedureStatus() == 4) {

			/*
			 * int lastInterface = list.get(list.size()-1).composed.getInterface(); int
			 * lastCallSide = list.get(list.size()-1).composed.getCallSide(); if
			 * (lastInterface == 18 && lastCallSide == 1) { serviceScenario = "主叫ISC"; }
			 * else { if(list.size()>1){ serviceScenario =
			 * Interface.getName(list.get(list.size() - 2).composed.getInterface()) + "-" +
			 * Interface.getName(lastInterface); } }
			 */
			String interfaceName = "";
			for (int i = 0; i < length; i++) {
				Integer interfaceNum = list.get(i).composed.getInterface();
				Integer callSide = list.get(i).composed.getCallSide();
				if (interfaceNum == null)
					continue;
				if (interfaceNum == 18 && callSide == 1) {
					interfaceName = "主叫ISC";
				} else if (interfaceNum == 18 && callSide == 2) {
					interfaceName = "被叫ISC";
				} else {
					interfaceName = Interface.getName(interfaceNum);
				}
				serviceScenario += interfaceName + "-";
			}
			serviceScenario = serviceScenario.substring(0, serviceScenario.length() - 1);
		}
		// }
		return serviceScenario;
	}

}